package com.kc.data.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.Data;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ImagesUtils {
    /**
     *
     * 获取图片宽高尺寸
     * @param fileUrl
     * @return
     */
    public static Map<String,Integer> getImgSize(String fileUrl) throws IOException {
//        InputStream is = new URL(fileUrl).openStream();
//        BufferedImage sourceImg = ImageIO.read(is);
//        int width = sourceImg.getWidth();
//        int height = sourceImg.getHeight();
//        Map<String,Integer> map = new HashMap<>();
//        map.put("width",width);
//        map.put("height",height);
//        return map;
        return getImgWidthAndHeight(fileUrl);
    }
    /**
     * OSS获取图片宽高
     * @param fileUrl
     * @return
     */
    public static Map<String,Integer> getImgWidthAndHeight(String fileUrl){
        @Data
        class ImgSize{
            private Map<String,Integer> ImageHeight;
            private Map<String,Integer> ImageWidth;
        }
        Map<String,Integer> map = new HashMap<>();
        RestTemplate restTemplate = new RestTemplate();
        fileUrl = fileUrl+"?x-oss-process=image/info";
        ResponseEntity<String> forEntity = restTemplate.getForEntity(fileUrl,String.class);
        try {
            ImgSize imgSize = JSONObject.parseObject(forEntity.getBody(), new TypeReference<ImgSize>() {
            });
            map.put("width",imgSize.getImageWidth().get("value"));
            map.put("height",imgSize.getImageHeight().get("value"));
        }catch (Exception e){
            map.put("width",0);
            map.put("height",0);
        }
        return map;
    }
}
